package crud;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 * Lop hien thuc cho cac chuc nang cua cac EntityCRUD
 * 
 * @author pokoyo
 */
public abstract class AbstractGRUD<T> {
	private Class<T> entityClass;
	private EntityManagerFactory fac;
	private EntityManager em;
	private String persistenceName = "GoodHealth-jpa";

	public EntityManager getEm() {
		EntityManager e = em;
		return e;
	}

	public AbstractGRUD(Class<T> entityClass) {
		fac = Persistence.createEntityManagerFactory(persistenceName);
		em = fac.createEntityManager();
		this.entityClass = entityClass;
	}

	public String create(T entity) {
		String result = "success";
		try {
			em.getTransaction().begin();
			em.persist(entity);
			em.getTransaction().commit();
		} catch (Exception e) {
			result = e.getMessage();
		}
		return result;
	}

	public String update(T entity) {
		String result = "success";
		try {
			em.getTransaction().begin();
			em.merge(entity);
			em.getTransaction().commit();
			em.refresh(entity);
		} catch (Exception e) {
			result = e.getMessage();
		}
		return result;
	}

	public String delete(T entity) {
		String result = "success";
		try {
			em.getTransaction().begin();
			em.remove(em.merge(entity));
			em.getTransaction().commit();
		} catch (Exception e) {
			result = e.getMessage();
		}
		return result;
	}

	public T readById(Object id) {
		T entity = em.find(entityClass, id);
		em.refresh(entity);
		return entity;
	}

	// lay toan bo danh sach entity
	public List<T> readAll() {
		return readAll(-1, 0);
	}

	// lay danh sach entity gioi han
	@SuppressWarnings("unchecked")
	public List<T> readAll(int max, int first) {		
		List<T> result = new ArrayList<T>();
		try {
			String entityName = entityClass.getName().split("\\.")[1];
			Query query = em.createQuery("select l from " + entityName + " l");
			if (max > -1) {
				query.setFirstResult(first);
				query.setMaxResults(max);
			}

			result = query.getResultList();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return result;

	}

	@SuppressWarnings("unchecked")
	public List<T> readByQuery(String queryString) {
		List<T> result = new ArrayList<T>();
		try {
			Query query = em.createQuery(queryString);

			result = query.getResultList();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return result;

	}

}
